﻿using Prism.Mvvm;
using System.Collections.ObjectModel;
using ModuleBase;
using HostComputerPlatform.Services;
using System.ComponentModel;
using Prism.Ioc;
using System.Diagnostics;
using System.Linq;
using Syncfusion.UI.Xaml.Diagram;
using ModuleBase.googoltech.GTS;
using Newtonsoft.Json;
using NLog;
using System.Net.Sockets;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using HostComputerPlatform.Views;
using System;
using System.Windows;
using Prism.Commands;
using Prism.Services.Dialogs;
using Newtonsoft.Json.Linq;
using HostComputerPlatform.Models;
using Prism.Events;
using System.Windows.Input;
using GTSCardSetDo;
using System.Text.Json;
using System.IO;
using System.Collections.Specialized;
using System.ComponentModel.DataAnnotations;
using System.Windows.Data;
using System.Timers;

namespace HostComputerPlatform.ViewModels
{
    public class MainWindowViewModel : BindableBase
    {
        private CancellationTokenSource source0, source1;
        private IAxisCardService _axisCardService;
        private ModuleStateService _moduleStateService;
        private ObservableCollection<bool> EXI = new ObservableCollection<bool>();
        private bool StartButton = false, ResetButton = false, EMGButton = false, PauseButton = false;
        private bool startButton = false, resetButton = false, eMGButton = false, pauseButton = false;
        private bool PauseFlag = false;
        Stopwatch sw = new Stopwatch();
        private bool isSystemDialogShow = false, isCameraCalibDialogShow = false;
        private readonly IDialogService _dialogService;
        private readonly IEventAggregator _eventAggregator;

        private IModuleBase _selectedModule;
        public IModuleBase SelectedModule
        {
            get => _selectedModule;
            set
            {
                if (_selectedModule != value)
                {
                    _selectedModule = value;
                    OnPropertyChanged(nameof(SelectedModule));
                }
            }
        }
        private bool isWindowFocused;
        public bool IsWindowFocused
        {
            get { return isWindowFocused; }
            set { SetProperty(ref isWindowFocused, value); }
        }
        private string _messageStr;
        public string MessageStr
        {
            get => _messageStr;
            set => SetProperty(ref _messageStr, value);
        }
        private int _selectedRowIndex = -1;
        public int SelectedRowIndex
        {
            get => _selectedRowIndex;
            set
            {
                if (SetProperty(ref _selectedRowIndex, value))
                {
                    _eventAggregator.GetEvent<UpdateTableEvent>().Publish();
                }
            }
        }

        public ObservableCollection<LogicTableRow> LogicTableRows { get; } = new ObservableCollection<LogicTableRow>();
        public ObservableCollection<NodeViewModel> Nodes { get; set; }
        public ObservableCollection<ConnectorViewModel> Connectors { get; set; }

        public IContainerProvider _containerProvider;
        private readonly CustomModuleManager _moduleManager;

        public ObservableCollection<IModuleBase> AvailableModules { get; set; } = new ObservableCollection<IModuleBase>();
        public ObservableCollection<string> ModuleCategories { get; set; } = new ObservableCollection<string>();

        private IExecutionFlowService _executionFlowService;
        public IExecutionFlowService ExecutionFlowService => _executionFlowService;
        private DelegateCommand appLoadedEventCommand;
        public DelegateCommand AppLoadedEventCommand =>
            appLoadedEventCommand ?? (appLoadedEventCommand = new DelegateCommand(ExecuteAppLoadedEventCommand));
        private DelegateCommand appClosedEventCommand;
        public DelegateCommand AppClosedEventCommand =>
            appClosedEventCommand ?? (appClosedEventCommand = new DelegateCommand(ExecuteAppClosedEventCommand));
        private DelegateCommand systemParamCommand;
        public DelegateCommand SystemParamCommand =>
            systemParamCommand ?? (systemParamCommand = new DelegateCommand(ExecuteSystemParamCommand));
        private DelegateCommand<object> camerabuttonCommand;
        public DelegateCommand<object> CamerabuttonCommand =>
            camerabuttonCommand ?? (camerabuttonCommand = new DelegateCommand<object>(ExecuteCamerabuttonCommand));
        private DelegateCommand testButtonCommand;
        public DelegateCommand TestButtonCommand =>
            testButtonCommand ?? (testButtonCommand = new DelegateCommand(ExecuteTestButtonCommand));
        private DelegateCommand stopButtonCommand;
        public DelegateCommand StopButtonCommand =>
            stopButtonCommand ?? (stopButtonCommand = new DelegateCommand(ExecuteStopButtonCommand));
        private DelegateCommand<object> operateCommand;
        public DelegateCommand<object> OperateCommand =>
            operateCommand ?? (operateCommand = new DelegateCommand<object>(ExecuteOperateCommand));
        private DelegateCommand saveCommand;
        public DelegateCommand SaveCommand =>
            saveCommand ?? (saveCommand = new DelegateCommand(ExecuteSaveCommand));
        private DelegateCommand loadCommand;
        public DelegateCommand LoadCommand =>
            loadCommand ?? (loadCommand = new DelegateCommand(ExecuteLoadCommand));

        private string _programFlowChartImagePath;
        public string ProgramFlowChartImagePath
        {
            get => _programFlowChartImagePath;
            set => SetProperty(ref _programFlowChartImagePath, value);
        }

        private ICollectionView _availableModulesGrouped;
        public ICollectionView AvailableModulesGrouped
        {
            get => _availableModulesGrouped;
            set
            {
                if (_availableModulesGrouped != value)
                {
                    _availableModulesGrouped = value;
                    OnPropertyChanged(nameof(AvailableModulesGrouped));
                }
            }
        }

        // 新增：已实例化模块集合
        public ObservableCollection<IModuleBase> InstantiatedModules { get; set; } = new ObservableCollection<IModuleBase>();

        private string _projectName = "";
        public string ProjectName
        {
            get => _projectName;
            set
            {
                if (_projectName != value)
                {
                    _projectName = value;
                    OnPropertyChanged(nameof(ProjectName));
                }
            }
        }

        public ObservableCollection<Variable> VariableLibrary { get; set; } = new ObservableCollection<Variable>();

        // 新增属性和命令
        public string RunStopButtonText => HostComputerPlatform.Services.GlobalStateService.Instance.CurrentState == HostComputerPlatform.Models.DeviceState.Running ? "停止" : "运行";
        public ICommand RunStopCommand => new Prism.Commands.DelegateCommand(() =>
        {
            if (HostComputerPlatform.Services.GlobalStateService.Instance.CurrentState == HostComputerPlatform.Models.DeviceState.Running)
                HostComputerPlatform.Services.GlobalStateService.Instance.Stop();
            else
                HostComputerPlatform.Services.GlobalStateService.Instance.Start();
        });
        public string EmergencyResumeButtonText => HostComputerPlatform.Services.GlobalStateService.Instance.CurrentState == HostComputerPlatform.Models.DeviceState.EmergencyStopped ? "恢复" : "急停";
        public ICommand EmergencyResumeCommand => new Prism.Commands.DelegateCommand(() =>
        {
            if (HostComputerPlatform.Services.GlobalStateService.Instance.CurrentState == HostComputerPlatform.Models.DeviceState.EmergencyStopped)
                HostComputerPlatform.Services.GlobalStateService.Instance.Resume();
            else
                HostComputerPlatform.Services.GlobalStateService.Instance.EmergencyStop();
        });
        public string StateText
        {
            get
            {
                var state = HostComputerPlatform.Services.GlobalStateService.Instance.CurrentState;
                switch (state)
                {
                    case HostComputerPlatform.Models.DeviceState.Idle: return "待机";
                    case HostComputerPlatform.Models.DeviceState.Running: return "运行中";
                    case HostComputerPlatform.Models.DeviceState.Paused: return "暂停";
                    case HostComputerPlatform.Models.DeviceState.EmergencyStopped: return "急停";
                    default: return "未知";
                }
            }
        }

        // 三级联动属性
        private string _selectedCategory;
        public string SelectedCategory
        {
            get => _selectedCategory;
            set
            {
                if (SetProperty(ref _selectedCategory, value))
                {
                    SelectedModuleType = null;
                    SelectedInstanceId = null;
                    RaisePropertyChanged(nameof(FilteredModuleTypes));
                    RaisePropertyChanged(nameof(FilteredInstancesWithNewOption));
                }
            }
        }
        private string _selectedModuleType;
        public string SelectedModuleType
        {
            get => _selectedModuleType;
            set
            {
                if (SetProperty(ref _selectedModuleType, value))
                {
                    SelectedInstanceId = null;
                    RaisePropertyChanged(nameof(FilteredInstancesWithNewOption));
                }
            }
        }
        private string _selectedInstanceId;
        public string SelectedInstanceId
        {
            get => _selectedInstanceId;
            set
            {
                if (SetProperty(ref _selectedInstanceId, value))
                {
                    // 选择"新增实例"时自动创建
                    if (_selectedInstanceId == "新增实例")
                    {
                        var moduleType = AvailableModules.FirstOrDefault(m => m.Name == SelectedModuleType && m.Category == SelectedCategory)?.GetType();
                        if (moduleType != null)
                        {
                            var newModule = _containerProvider.Resolve(moduleType) as IModuleBase;
                            newModule.TemplateName = SelectedModuleType;
                            newModule.Name = SelectedModuleType + "_" + (InstantiatedModules.Count(m => m.TemplateName == SelectedModuleType) + 1);
                            newModule.Category = SelectedCategory;
                            InstantiatedModules.Add(newModule);
                            var debugMsg = $"[调试] 新增实例: Name={newModule.Name}, TemplateName={newModule.TemplateName}, Category={newModule.Category}, Id={newModule.Id}";
                            MyFunc.AddMessage(debugMsg);
                            MessageStr += debugMsg + "\n";
                            RaisePropertyChanged(nameof(MessageStr));
                            System.Windows.MessageBox.Show(MessageStr, "MessageStr调试输出");
                            foreach (var m in InstantiatedModules)
                            {
                                var msg = $"[调试] 实例: Name={m.Name}, TemplateName={m.TemplateName}, Category={m.Category}, Id={m.Id}";
                                MyFunc.AddMessage(msg);
                                MessageStr += msg + "\n";
                            }
                            var selectMsg = $"[调试] 当前选中: Category={SelectedCategory}, ModuleType={SelectedModuleType}";
                            MyFunc.AddMessage(selectMsg);
                            MessageStr += selectMsg + "\n";
                            RaisePropertyChanged(nameof(MessageStr));
                            SelectedInstanceId = newModule.Id;
                        }
                    }
                }
            }
        }
        // 过滤后的类型列表
        public IEnumerable<string> FilteredModuleTypes =>
            string.IsNullOrEmpty(SelectedCategory)
                ? Enumerable.Empty<string>()
                : AvailableModules.Where(m => m.Category == SelectedCategory).Select(m => m.Name).Distinct().ToList();
        // 过滤后的实例列表+新增实例
        public IEnumerable<object> FilteredInstancesWithNewOption =>
            string.IsNullOrEmpty(SelectedModuleType)
                ? Enumerable.Empty<object>()
                : InstantiatedModules.Where(m => m.TemplateName == SelectedModuleType && m.Category == SelectedCategory)
                    .Select(m => new { Name = m.DisplayName, Id = m.Id })
                    .Concat(new[] { new { Name = "新增实例", Id = "新增实例" } })
                    .ToList();

        void ExecuteLoadCommand()
        {
            var dialog = new SelectSaveLoadModeDialogWindow("请选择加载方式");
            dialog.Owner = System.Windows.Application.Current.MainWindow;
            if (dialog.ShowDialog() == true)
            {
                if (dialog.SelectedMode == SelectSaveLoadModeDialogWindow.SaveLoadMode.SingleFile)
                {
                    Microsoft.Win32.OpenFileDialog openFileDialog = new Microsoft.Win32.OpenFileDialog();
                    openFileDialog.Filter = "JSON files (*.json)|*.json";
                    if (openFileDialog.ShowDialog() == true)
                    {
                        LoadExecutionFlow(openFileDialog.FileName);
                    }
                }
                else // ProjectFolder
                {
                    var folderDialog = new System.Windows.Forms.FolderBrowserDialog();
                    folderDialog.Description = "请选择项目文件夹（将自动加载logic.json和flowchart.png）";
                    if (folderDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                    {
                        string folder = folderDialog.SelectedPath;
                        string logicPath = System.IO.Path.Combine(folder, "logic.json");
                        string flowchartPath = System.IO.Path.Combine(folder, "flowchart.png");
                        LoadExecutionFlow(logicPath);
                        if (File.Exists(flowchartPath))
                        {
                            ProgramFlowChartImagePath = flowchartPath;
                        }
                    }
                }
            }
        }
        void ExecuteSaveCommand()
        {
            var dialog = new SelectSaveLoadModeDialogWindow("请选择保存方式");
            dialog.Owner = System.Windows.Application.Current.MainWindow;
            if (dialog.ShowDialog() == true)
            {
                if (dialog.SelectedMode == SelectSaveLoadModeDialogWindow.SaveLoadMode.SingleFile)
                {
                    Microsoft.Win32.SaveFileDialog saveFileDialog = new Microsoft.Win32.SaveFileDialog();
                    saveFileDialog.Filter = "JSON files (*.json)|*.json";
                    if (saveFileDialog.ShowDialog() == true)
                    {
                        SaveExecutionFlow(saveFileDialog.FileName);
                    }
                }
                else // ProjectFolder
                {
                    var folderDialog = new System.Windows.Forms.FolderBrowserDialog();
                    folderDialog.Description = "请选择项目文件夹（将保存logic.json和flowchart.png）";
                    if (folderDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                    {
                        string folder = folderDialog.SelectedPath;
                        SaveExecutionFlow(System.IO.Path.Combine(folder, "logic.json"));
                        if (!string.IsNullOrEmpty(ProgramFlowChartImagePath) && File.Exists(ProgramFlowChartImagePath))
                        {
                            File.Copy(ProgramFlowChartImagePath, System.IO.Path.Combine(folder, "flowchart.png"), true);
                        }
                    }
                }
            }
        }
        public ICommand AvailableModulesDoubleClickCommand { get; }
        public ICommand RenameModuleCommand { get; }
        public ICommand DeleteModuleCommand { get; }
        void ExecuteOperateCommand(object obj)
        {
            switch (obj.ToString())
            {
                case "添加":
                    AddNewRow();
                    break;
                case "删除":
                    if (SelectedRowIndex >= 0)
                    {
                        LogicTableRows.RemoveAt(SelectedRowIndex);
                        SelectedRowIndex = Math.Min(SelectedRowIndex, LogicTableRows.Count - 1);
                    }
                    break;
                case "上移":
                    if (SelectedRowIndex > 0)
                    {
                        MoveRow(SelectedRowIndex, SelectedRowIndex - 1);
                        SelectedRowIndex--;
                    }
                    break;
                case "下移":
                    if (SelectedRowIndex < LogicTableRows.Count - 1)
                    {
                        MoveRow(SelectedRowIndex, SelectedRowIndex + 1);
                        SelectedRowIndex++;
                    }
                    break;
            }
        }
        void ExecuteStopButtonCommand()
        {
            PauseFlag = true;
            GTSCard.AxisStop(_axisCardService.A1, 0);
            GTSCard.AxisStop(_axisCardService.A2, 0);
            GTSCard.AxisStop(_axisCardService.A3, 0);
            GTSCard.AxisStop(_axisCardService.A4, 0);
            GTSCard.AxisStop(_axisCardService.A5, 0);
            GTSCard.AxisStop(_axisCardService.A6, 0);
            GTSCard.AxisStop(_axisCardService.A7, 0);
            GTSCard.AxisStop(_axisCardService.A8, 0);
        }
        void ExecuteTestButtonCommand()
        {
            source1 = new CancellationTokenSource();
            CancellationToken token = source1.Token;

            Task.Run(() => LeftHome(token), token);
            Task.Run(() => RightHome(token), token);
        }
        void ExecuteCamerabuttonCommand(object obj)
        {
            int HandIndex = 0;
            switch (obj.ToString())
            {
                case "Camera1":
                    HandIndex = 0;
                    break;
                case "Camera2":
                    HandIndex = 1;
                    break;
                case "Camera3":
                    HandIndex = 2;
                    break;
                case "Camera4":
                    HandIndex = 3;
                    break;
            }
            if (!isCameraCalibDialogShow)
            {
                isCameraCalibDialogShow = true;
                DialogParameters param = new DialogParameters();
                param.Add("HandIndex", HandIndex);
                _dialogService.ShowDialog("CameraCalibDialog", param, arg =>
                {
                    isCameraCalibDialogShow = false;
                    IsWindowFocused = !IsWindowFocused;
                });
            }
        }
        void ExecuteSystemParamCommand()
        {
            if (!isSystemDialogShow)
            {
                isSystemDialogShow = true;
                DialogParameters param = new DialogParameters();
                _dialogService.ShowDialog("SystemDialogView", param, arg =>
                {
                    isSystemDialogShow = false;
                    IsWindowFocused = !IsWindowFocused;
                });
            }
        }
        async void ExecuteAppClosedEventCommand()
        {
            source0?.Cancel();
            source0?.Dispose();
        }
        private void ExecuteAppLoadedEventCommand()
        {
            source0 = new CancellationTokenSource();
            CancellationToken token = source0.Token;
            Task.Run(() => Run(token), token);
            Task.Run(() => RunFlow(token), token);
        }

        public MainWindowViewModel(IExecutionFlowService executionFlowService, IContainerProvider containerProvider, CustomModuleManager moduleManager, IAxisCardService axisCardService, ModuleStateService moduleStateService, IEventAggregator eventAggregator)
        {
            RenameModuleCommand = new DelegateCommand<IModuleBase>(OnRenameModule);
            DeleteModuleCommand = new DelegateCommand<IModuleBase>(OnDeleteModule);
            _dialogService = containerProvider.Resolve<IDialogService>();
            _executionFlowService = executionFlowService;
            _containerProvider = containerProvider ?? throw new ArgumentNullException(nameof(containerProvider));
            _moduleManager = moduleManager ?? throw new ArgumentNullException(nameof(moduleManager));
            _eventAggregator = eventAggregator;
            axisCardService = containerProvider.Resolve<IAxisCardService>();
            _axisCardService = axisCardService;
            LoadAvailableModules();
            {
                AvailableModules.Add(new AxisMoveModel.AxisMoveModule(containerProvider, moduleStateService) { Category = "运动控制" });
                AvailableModules.Add(new AxisMovePoint.AxisMovePoint(containerProvider, moduleStateService) { Category = "运动控制" });
                AvailableModules.Add(new InitAxis.InitAxis(containerProvider) { Category = "运动控制" });
                AvailableModules.Add(new ModbusCon.ModbusCon(containerProvider) { Category = "通讯与IO" });
                AvailableModules.Add(new AxisHome.AxisHome(containerProvider, moduleStateService) { Category = "运动控制" });
                AvailableModules.Add(new AxisSerOn.AxisSerOn(containerProvider) { Category = "运动控制" });
                AvailableModules.Add(new GetPulseValue.GetPulseValue(containerProvider) { Category = "运动控制" });
                AvailableModules.Add(new AxisStop.AxisStop(containerProvider, moduleStateService) { Category = "运动控制" });
                AvailableModules.Add(new CameraCon.CameraCon(containerProvider) { Category = "相机与视觉" });
                AvailableModules.Add(new GetDi.GetDi() { Category = "通讯与IO" });
                AvailableModules.Add(new GTSCardSetDo.GTSCardSetDo() { Category = "运动控制" });
                AvailableModules.Add(new ThreadSleep.ThreadSleep() { Category = "逻辑与流程" });
                AvailableModules.Add(new FlyGrabAction.FlyGrabAction(containerProvider, moduleStateService) { Category = "相机与视觉" });
            }
            AvailableModules = new ObservableCollection<IModuleBase>(AvailableModules.OrderBy(m => m.Name));

            _moduleStateService = moduleStateService;
            Nodes = new ObservableCollection<NodeViewModel>();
            Connectors = new ObservableCollection<ConnectorViewModel>();
            EXI = new ObservableCollection<bool>();
            for (int i = 0; i < 7; i++)
            {
                EXI.Add(false);
            }

            AvailableModules.CollectionChanged += (s, e) =>
            {
                AvailableModulesGrouped?.Refresh();
                OnPropertyChanged(nameof(AvailableModulesGrouped));
            };
            AvailableModulesGrouped = CollectionViewSource.GetDefaultView(AvailableModules);
            AvailableModulesGrouped.GroupDescriptions.Clear();
            AvailableModulesGrouped.GroupDescriptions.Add(new PropertyGroupDescription("Category"));

            // 初始化类型列表
            var categories = AvailableModules.Select(m => m.Category).Distinct().ToList();
            ModuleCategories.Clear();
            foreach (var cat in categories)
                ModuleCategories.Add(cat);

            // 订阅全局状态服务的控制信号
            HostComputerPlatform.Services.GlobalStateService.Instance.ControlSignal += signal =>
            {
                switch (signal)
                {
                    case "emergencystopped":
                        _moduleStateService.StopAllModules();
                        ExecutionFlowService.StopExecution();
                        break;
                    case "paused":
                        ExecutionFlowService.PauseExecution();
                        _moduleStateService.StopAllModules();
                        break;
                    case "running":
                        ExecutionFlowService.ResumeExecution();
                        _moduleStateService.Reset();
                        break;
                    case "idle":
                        _moduleStateService.Reset();
                        break;
                }
            };

            HostComputerPlatform.Services.GlobalStateService.Instance.StateChanged += () =>
            {
                RaisePropertyChanged(nameof(RunStopButtonText));
                RaisePropertyChanged(nameof(EmergencyResumeButtonText));
                RaisePropertyChanged(nameof(StateText));
            };

            // 自动同步MyFunc.MessageStr到MessageStr，确保执行日志窗口实时刷新
            System.Timers.Timer logTimer = new System.Timers.Timer(200);
            logTimer.Elapsed += (s, e) =>
            {
                if (MessageStr != ModuleBase.MyFunc.MessageStr)
                {
                    MessageStr = ModuleBase.MyFunc.MessageStr;
                    RaisePropertyChanged(nameof(MessageStr));
                }
            };
            logTimer.Start();
        }

        public async Task StartExecutionFlow()
        {
            // 构建执行列表，这里假设 LogicTableRows 包含了所需信息
            var executionList = GetExecutionList();
            // 这里假设 ExecutionFlowService 的构造函数需要执行列表作为参数
            _executionFlowService = new ExecutionFlowService(executionList);
            await _executionFlowService.ExecuteFlowAsync();
        }

        private List<(List<IModuleBase> modules, ObservableCollection<EditableItem> trueBranch, ObservableCollection<EditableItem> falseBranch)> GetExecutionList()
        {
            // 按序号（集合索引 + 1）对 LogicTableRows 进行排序
            var sortedRows = LogicTableRows.Select((row, index) => new { Row = row, Index = index + 1 })
                                           .OrderBy(item => item.Index)
                                           .Select(item => item.Row)
                                           .ToList();

            var executionList = new List<(List<IModuleBase> modules, ObservableCollection<EditableItem> trueBranch, ObservableCollection<EditableItem> falseBranch)>();

            foreach (var row in sortedRows)
            {
                var modules = row.SourceModule
                   .Select(item => AvailableModules.FirstOrDefault(m => m.GetType().FullName == item.Content))
                   .Where(module => module != null)
                   .ToList();

                executionList.Add((modules, row.TrueBranch, row.FalseBranch));
            }

            return executionList;
        }
        public void SaveExecutionFlow(string filePath)
        {
            try
            {
                var flowData = new ExecutionFlowData();

                // 保存所有已使用的模块信息
                foreach (var module in AvailableModules)
                {
                    var moduleData = new ModuleData
                    {
                        TypeName = module.GetType().FullName,
                        Id = module.Id,
                        Name = module.Name,
                        Properties = module.GetProperties()
                    };
                    flowData.Modules.Add(moduleData);
                }

                // 保存逻辑表行信息
                foreach (var row in LogicTableRows)
                {
                    var rowData = new LogicTableRowData();

                    // 保存源模块
                    foreach (var moduleItem in row.SourceModule)
                    {
                        if (!string.IsNullOrEmpty(moduleItem.Content))
                        {
                            rowData.SourceModuleIds.Add(moduleItem.Content);
                        }
                    }

                    // 保存分支信息
                    if (row.TrueBranch.Count > 0 && !string.IsNullOrEmpty(row.TrueBranch[0].Content))
                    {
                        rowData.TrueBranch = row.TrueBranch[0].Content;
                    }

                    if (row.FalseBranch.Count > 0 && !string.IsNullOrEmpty(row.FalseBranch[0].Content))
                    {
                        rowData.FalseBranch = row.FalseBranch[0].Content;
                    }

                    flowData.Rows.Add(rowData);
                }

                // 序列化为JSON并保存
                var options = new JsonSerializerOptions
                {
                    WriteIndented = true,
                    Converters = { new System.Text.Json.Serialization.JsonStringEnumConverter() }
                };

                string json = System.Text.Json.JsonSerializer.Serialize(flowData, options);
                File.WriteAllText(filePath, json);

                MyFunc.AddMessage($"{filePath} 保存成功");
            }
            catch (Exception ex)
            {
                MyFunc.AddMessage($"{filePath} 保存失败: {ex.Message}");
            }
        }
        public void LoadExecutionFlow(string filePath)
        {
            try
            {
                if (!File.Exists(filePath))
                {
                    MyFunc.AddMessage($"文件不存在: {filePath}");
                    return;
                }

                string json = File.ReadAllText(filePath);
                var flowData = System.Text.Json.JsonSerializer.Deserialize<ExecutionFlowData>(json);

                if (flowData == null)
                {
                    MyFunc.AddMessage("加载失败: 文件格式不正确");
                    return;
                }

                // 清空当前状态
                AvailableModules.Clear();
                LogicTableRows.Clear();

                // 创建模块名称到类型的映射
                var moduleTypeMap = AvailableModules.ToDictionary(
                    m => m.GetType().FullName,
                    m => m.GetType());

                // 重新实例化所有模块
                var moduleInstances = new Dictionary<string, IModuleBase>();
                foreach (var moduleData in flowData.Modules)
                {
                    try
                    {
                        // 从模块库中查找类型
                        if (!moduleTypeMap.TryGetValue(moduleData.TypeName, out Type moduleType))
                        {
                            MyFunc.AddMessage($"模块类型不在当前模块库中: {moduleData.TypeName}");
                            continue;
                        }

                        // 创建模块实例
                        var module = _containerProvider.Resolve(moduleType) as IModuleBase;
                        module.Id = moduleData.Id;
                        module.Name = moduleData.Name;

                        // 设置模块属性
                        module.SetProperties(moduleData.Properties);

                        AvailableModules.Add(module);
                        moduleInstances[moduleData.Id] = module;
                    }
                    catch (Exception ex)
                    {
                        MyFunc.AddMessage($"加载模块 {moduleData.Name} 失败: {ex.Message}");
                    }
                }

                // 重建逻辑表
                foreach (var rowData in flowData.Rows)
                {
                    var newRow = new LogicTableRow();

                    // 添加源模块
                    foreach (var moduleId in rowData.SourceModuleIds)
                    {
                        if (moduleInstances.TryGetValue(moduleId, out var module))
                        {
                            newRow.SourceModule.Add(new EditableItem(item => newRow.SourceModule.Remove(item))
                            {
                                Content = moduleId
                            });
                        }
                    }

                    // 添加分支信息
                    if (rowData.TrueBranch != "无")
                    {
                        newRow.TrueBranch.Add(new EditableItem(item => newRow.TrueBranch.Remove(item))
                        {
                            Content = rowData.TrueBranch
                        });
                    }

                    if (rowData.FalseBranch != "无")
                    {
                        newRow.FalseBranch.Add(new EditableItem(item => newRow.FalseBranch.Remove(item))
                        {
                            Content = rowData.FalseBranch
                        });
                    }

                    LogicTableRows.Add(newRow);
                }

                MyFunc.AddMessage($"{filePath} 加载成功");
                _eventAggregator.GetEvent<UpdateTableEvent>().Publish();
            }
            catch (Exception ex)
            {
                MyFunc.AddMessage($"{filePath} 加载失败: {ex.Message}");
            }
        }
        private void OnDeleteModule(IModuleBase module)
        {
            if (module == null) return;
            var result = System.Windows.MessageBox.Show(
                $"确定要删除模块 '{module.Name}' 吗?\n所有使用此模块的单元格将被清空",
                "确认删除",
                MessageBoxButton.YesNo,
                MessageBoxImage.Question);

            if (result == MessageBoxResult.Yes)
            {
                AvailableModules.Remove(module);
                AvailableModulesGrouped?.Refresh();
                OnPropertyChanged(nameof(AvailableModulesGrouped));

                ClearModuleReferences(module.Id);

                if (SelectedModule == module)
                {
                    SelectedModule = null;
                }
                _eventAggregator.GetEvent<UpdateTableEvent>().Publish();
                System.Windows.Input.CommandManager.InvalidateRequerySuggested();
            }
        }

        private void ClearModuleReferences(string moduleId)
        {
            foreach (var row in LogicTableRows)
            {
                ClearModuleFromCollection(row.SourceModule, moduleId);
            }
        }

        private void ClearModuleFromCollection(ObservableCollection<EditableItem> collection, string moduleId)
        {
            // 找出所有引用了该模块的项
            var itemsToClear = collection
                .Where(item => item.Content == moduleId.ToString())
                .ToList();

            foreach (var item in itemsToClear)
            {
                item.Content = string.Empty;
            }
        }
        private void OnRenameModule(IModuleBase module)
        {
            if (module == null) return;

            var dialog = new InputDialogWindow(
                title: "重命名模块",
                prompt: "请输入新的模块名称:",
                defaultValue: module.Name)
            {
                Owner = System.Windows.Application.Current.MainWindow // 设置父窗口
            };

            if (dialog.ShowDialog() == true && !string.IsNullOrWhiteSpace(dialog.InputText))
            {
                string newName = dialog.InputText.Trim();

                // 检查名称是否已存在
                if (AvailableModules.Any(m => m != module && m.Name.Equals(newName, StringComparison.OrdinalIgnoreCase)))
                {
                    System.Windows.MessageBox.Show("该名称已存在，请使用其他名称", "名称冲突",
                         MessageBoxButton.OK, MessageBoxImage.Warning);
                    return;
                }

                module.Name = newName;
                AvailableModulesGrouped?.Refresh();
                OnPropertyChanged(nameof(AvailableModulesGrouped));
            }
        }
        private void LoadAvailableModules()
        {
            AvailableModules.Clear();
            var moduleTypes = _moduleManager.LoadModules();

            foreach (var moduleType in moduleTypes)
            {
                var module = _moduleManager.CreateModuleInstance(moduleType);
                if (!AvailableModules.Any(m => m.GetType() == moduleType))
                {
                    AvailableModules.Add(module);
                    SubscribeToModuleEvents(module);
                }
            }
            AvailableModulesGrouped?.Refresh();
            OnPropertyChanged(nameof(AvailableModulesGrouped));
        }
        private async Task Run(CancellationToken token)
        {
            while (true)
            {
                if (token.IsCancellationRequested)
                {
                    return;
                }
                if (!_axisCardService.Connected)
                {
                    Thread.Sleep(1000);
                    continue;
                }
                try
                {
                    var diport = GTSCard.GetDiPort1((short)_axisCardService.A1.CardNo);
                    for (int i = 0; i < 7; i++)
                    {
                        EXI[i] = (diport & 1 << i) != 0;
                    }
                    // 只在信号变化时调用全局状态服务
                    if (eMGButton != EXI[0])
                    {
                        eMGButton = EXI[0];
                        if (eMGButton)
                            HostComputerPlatform.Services.GlobalStateService.Instance.SetStateFromExternal(HostComputerPlatform.Models.DeviceState.EmergencyStopped);
                        else
                            HostComputerPlatform.Services.GlobalStateService.Instance.SetStateFromExternal(HostComputerPlatform.Models.DeviceState.Idle);
                    }
                    if (startButton != EXI[1])
                    {
                        startButton = EXI[1];
                        if (startButton)
                            HostComputerPlatform.Services.GlobalStateService.Instance.SetStateFromExternal(HostComputerPlatform.Models.DeviceState.Running);
                    }
                    if (pauseButton != EXI[2])
                    {
                        pauseButton = EXI[2];
                        if (pauseButton)
                            HostComputerPlatform.Services.GlobalStateService.Instance.SetStateFromExternal(HostComputerPlatform.Models.DeviceState.Paused);
                    }
                    if (resetButton != EXI[3])
                    {
                        resetButton = EXI[3];
                        if (resetButton)
                            HostComputerPlatform.Services.GlobalStateService.Instance.SetStateFromExternal(HostComputerPlatform.Models.DeviceState.Idle);
                    }
                }
                catch (Exception ex)
                {
                }
            }
        }
        private async Task RunFlow(CancellationToken token)
        {
            // 只负责刷新界面消息，不再处理流程状态机
            while (true)
            {
                MessageStr = MyFunc.MessageStr;
                if (token.IsCancellationRequested)
                {
                    return;
                }
                if (!_axisCardService.Connected)
                {
                    Thread.Sleep(1000);
                    continue;
                }
                await Task.Delay(100); // 降低CPU占用
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;

        protected virtual void OnPropertyChanged(string propertyName)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }

        public void SubscribeToModuleEvents(IModuleBase module)
        {
            if (module != null)
            {
                module.ExecutionResultEvent += OnModuleExecutionResult;
            }
        }

        private void OnModuleExecutionResult(string message)
        {
            MyFunc.AddMessage(message);
        }
        private void LeftHome(CancellationToken token)
        {
            bool Homed = false;
            int stepnum = 0;
            var axisY = _axisCardService.A1;
            int actionCount = 0;
            while (true)
            {
                if (token.IsCancellationRequested)
                {
                    return;
                }
                switch (stepnum)
                {
                    case 0:
                        if (!Homed)
                        {
                            stepnum = 3;
                        }
                        else
                        {
                            MyFunc.AddMessage("Y1轴已回原点");
                            return;
                        }
                        break;
                    case 3:
                        if (!PauseFlag)
                        {
                            GTSCard.AxisHomeMove(axisY);
                            MyFunc.AddMessage("Y1轴回原点中");
                            stepnum = 4;
                        }
                        break;
                    case 4:
                        if (!PauseFlag)
                        {
                            if (GTSCard.AxisHomeCheckDone(axisY))
                            {
                                actionCount++;
                                if (actionCount > 1)
                                {
                                    System.Threading.Thread.Sleep(2000);
                                    GTSCard.AxisZeroSet(axisY);
                                    var _leftDelta = JsonConvert.DeserializeObject<MPoint>(Properties.Settings.Default.LeftDelta);
                                    GTSCard.AxisPosSet(axisY, _leftDelta.Y);
                                    GTSCard.AxisEncSet(axisY, _leftDelta.Y);
                                    GTSCard.AxisSynchAxisPos(axisY);
                                    GTSCard.SetSoftLimit(axisY);
                                    GTSCard.ClearAlm1(axisY);
                                    Homed = true;
                                    MyFunc.AddMessage("Y1轴回原点完成");
                                    return;
                                }
                                else
                                {
                                    GTSCard.AxisZeroSet(axisY);
                                    GTSCard.ClearAlm1(axisY);
                                    stepnum = 3;
                                }
                            }
                        }
                        else
                        {
                            GTSCard.AxisStop(axisY, 0);
                            stepnum = 3;
                        }
                        break;
                    default:
                        break;
                }
                System.Threading.Thread.Sleep(100);
            }
        }
        private void RightHome(CancellationToken token)
        {
            bool Homed = false;
            int stepnum = 0;
            var axisY = _axisCardService.A4;
            int actionCount = 0;
            while (true)
            {
                if (token.IsCancellationRequested)
                {
                    return;
                }
                switch (stepnum)
                {
                    case 0:
                        if (!Homed)
                        {
                            stepnum = 3;
                        }
                        else
                        {
                            MyFunc.AddMessage("Y2轴已回原点");
                            return;
                        }
                        break;
                    case 3:
                        if (!PauseFlag)
                        {
                            GTSCard.AxisHomeMove(axisY);
                            MyFunc.AddMessage("Y2轴回原点中");
                            stepnum = 4;
                        }
                        break;
                    case 4:
                        if (!PauseFlag)
                        {
                            if (GTSCard.AxisHomeCheckDone(axisY))
                            {
                                actionCount++;
                                if (actionCount > 1)
                                {
                                    System.Threading.Thread.Sleep(2000);
                                    GTSCard.AxisZeroSet(axisY);
                                    var _rightDelta = JsonConvert.DeserializeObject<MPoint>(Properties.Settings.Default.RightDelta);
                                    GTSCard.AxisPosSet(axisY, _rightDelta.Y);
                                    GTSCard.AxisEncSet(axisY, _rightDelta.Y);
                                    GTSCard.AxisSynchAxisPos(axisY);
                                    GTSCard.SetSoftLimit(axisY);
                                    GTSCard.ClearAlm1(axisY);
                                    Homed = true;
                                    MyFunc.AddMessage("Y2轴回原点完成");
                                    return;
                                }
                                else
                                {
                                    GTSCard.AxisZeroSet(axisY);
                                    GTSCard.ClearAlm1(axisY);
                                    stepnum = 3;
                                }
                            }
                        }
                        else
                        {
                            GTSCard.AxisStop(axisY, 0);
                            stepnum = 3;
                        }
                        break;
                    default:
                        break;
                }
                System.Threading.Thread.Sleep(100);
            }
        }

        private void AddNewRow()
        {
            var newRow = new LogicTableRow
            {
            };
            LogicTableRows.Add(newRow);
            SelectedRowIndex = LogicTableRows.Count - 1;
        }

        private void MoveRow(int oldIndex, int newIndex)
        {
            var item = LogicTableRows[oldIndex];
            LogicTableRows.Move(oldIndex, newIndex);
        }

        // 在添加操作时实例化新模块
        public void AddModuleToRow(LogicTableRow row, string category, string moduleName)
        {
            var moduleTemplate = AvailableModules.FirstOrDefault(m => m.Category == category && m.Name == moduleName);
            if (moduleTemplate != null)
            {
                var newModule = _containerProvider.Resolve(moduleTemplate.GetType()) as IModuleBase;
                newModule.TemplateName = moduleTemplate.Name;
                newModule.Name = moduleTemplate.Name;
                newModule.Category = moduleTemplate.Category;
                InstantiatedModules.Add(newModule);
                row.SourceModule.Add(new EditableItem(item => row.SourceModule.Remove(item))
                {
                    Content = newModule.Id
                });
                SelectedModule = newModule;
                // 调试弹窗显示所有实例信息
                string msg = "当前所有实例：\n";
                foreach (var m in InstantiatedModules)
                {
                    msg += $"Name={m.Name}, TemplateName={m.TemplateName}, Category={m.Category}, Id={m.Id}\n";
                }
                System.Windows.MessageBox.Show(msg, "AddModuleToRow调试");
            }
        }
        // 删除操作时移除实例
        public void RemoveModuleInstance(string moduleId)
        {
            var inst = InstantiatedModules.FirstOrDefault(m => m.Id == moduleId);
            if (inst != null)
                InstantiatedModules.Remove(inst);
        }

        public void SaveVariableLibrary(string filePath)
        {
            try
            {
                var options = new System.Text.Json.JsonSerializerOptions { WriteIndented = true };
                string json = System.Text.Json.JsonSerializer.Serialize(VariableLibrary, options);
                System.IO.File.WriteAllText(filePath, json);
            }
            catch (Exception ex)
            {
                MyFunc.AddMessage($"变量库保存失败: {ex.Message}");
            }
        }
        public void LoadVariableLibrary(string filePath)
        {
            try
            {
                if (!System.IO.File.Exists(filePath)) return;
                string json = System.IO.File.ReadAllText(filePath);
                var list = System.Text.Json.JsonSerializer.Deserialize<ObservableCollection<Variable>>(json);
                if (list != null)
                {
                    VariableLibrary.Clear();
                    foreach (var v in list)
                        VariableLibrary.Add(v);
                }
            }
            catch (Exception ex)
            {
                MyFunc.AddMessage($"变量库加载失败: {ex.Message}");
            }
        }
    }
    public class UpdateTableEvent : PubSubEvent { }
}